/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.SendMailUtil;
import com.thinkgem.jeesite.common.utils.excel.ExportCSV;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.service.*;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.oa.entity.OaNotify;
import com.thinkgem.jeesite.modules.oa.service.OaNotifyService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.*;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * 商品的ControllerController
 *
 * @author tiancheng
 * @version 2018-07-12
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizGoods")
public class BizGoodsController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
	@Autowired
	private BizGoodsService bizGoodsService;
	@Autowired
	private BizGoodsBrandService bizGoodsBrandService;
	@Autowired
	private BizSupplierService bizSupplierService;
	@Autowired
	private BizStorageService bizStorageService;
	@Autowired
	private OaNotifyService oaNotifyService;
	@Autowired
	private BizBarcodeService bizBarcodeService;


	@ModelAttribute
	public BizGoods get(@RequestParam(required = false) String id) {
		BizGoods entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = bizGoodsService.get(id);
		}
		if (entity == null) {
			entity = new BizGoods();
		}
		return entity;
	}

	@RequiresPermissions("biz:bizGoods:view")
	@RequestMapping(value = {"list", ""})
	public String list(BizGoods bizGoods, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BizGoods> page = bizGoodsService.findPage(new Page<BizGoods>(request, response), bizGoods);
		model.addAttribute("page", page);
		return "modules/biz/bizGoodsList";
	}

	@RequiresPermissions("biz:bizGoods:view")
	@RequestMapping(value = "form")
	public String form(BizGoods bizGoods, Model model) {
		model.addAttribute("bizGoods", bizGoods);
		//获取全部的商品品牌
		List<BizGoodsBrand> bizGoodsBrandList = bizGoodsBrandService.findAllList(new BizGoodsBrand());
		//供应商--审批成功的且启用的
		BizSupplier bizSupplier = new BizSupplier();
		bizSupplier.setAppState("15");
		bizSupplier.setIsEnable("1");
		List<BizSupplier> bizSupplierList = bizSupplierService.findList(bizSupplier);
		//仓库
		List<BizStorage> bizStorageList = bizStorageService.findList(new BizStorage());

		model.addAttribute("bizSupplierList", bizSupplierList);
		model.addAttribute("bizGoodsBrandList", bizGoodsBrandList);
		model.addAttribute("bizStorageList", bizStorageList);
		return "modules/biz/bizGoodsForm";
	}

	@RequiresPermissions(value = {"biz:bizGoods:add", "biz:bizGoods:edit"}, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(BizGoods bizGoods, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, bizGoods)) {
			return form(bizGoods, model);
		}
		bizGoodsService.save(bizGoods);
		addMessage(redirectAttributes, "保存商品成功");
		return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
	}

	@RequestMapping(value = "ajaxSave")
	@ResponseBody
	public String ajaxSave(HttpServletRequest request, BizGoods bizGoods) {
		String msg = "";
		String isCanSave = "yes";
		if(bizGoods != null){
			if(StringUtils.isEmpty(bizGoods.getGoodsId())){
				String goodsCode = bizGoods.getGoodsCode();
				if(StringUtils.isNotEmpty(goodsCode)){
					Integer count = bizGoodsService.findCountByGoodsCode(goodsCode);
					if(count != null && count > 0){
						msg = "codeRepeat";//编码重复
						isCanSave = "no";
					}
				}else{
					msg = "codeIsNull";
					isCanSave = "no";
				}
			}
			if("yes".equals(isCanSave)){
				try {
					bizGoodsService.save(bizGoods);
					msg = "success";
				} catch (Exception e) {
					//保存失败
					msg = "error";
				}
			}
		}
		return msg;
	}

	@RequestMapping(value = "checkCodeRepeat")
	@ResponseBody
	public String checkCodeRepeat(HttpServletRequest request, String goodsCode) {
		String msg = "";
		if(StringUtils.isNotEmpty(goodsCode)){
			Integer count = bizGoodsService.findCountByGoodsCode(goodsCode);
			if(count != null && count > 0){
				msg = "codeRepeat";//编码重复
			}
		}else{
			msg = "codeIsNull";
		}
		return msg;
	}



	@RequiresPermissions("biz:bizGoods:remove")
	@RequestMapping(value = "delete")
	public String delete(BizGoods bizGoods, RedirectAttributes redirectAttributes) {
		bizGoodsService.delete(bizGoods);
		addMessage(redirectAttributes, "删除商品成功");
		return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
	}


	/**
	 * 添加采购单时批量挑选商品
	 *
	 * @param
	 * @return
	 * @author tiancheng
	 * @date 2018/7/13 9:56
	 */
	@RequestMapping(value = "modalPage")
	@ResponseBody
	public Page<BizGoods> modalPage(BizGoods bizGoods, HttpServletRequest request, HttpServletResponse response) {
		Page<BizGoods> pageInfo = new Page<BizGoods>(request, response);
		pageInfo.setPageSize(10);
		Page<BizGoods> page = bizGoodsService.findPage(pageInfo, bizGoods);
		return page;
	}


	/**
	 * 获取商品的信息
	 *
	 * @param
	 * @return
	 * @author tiancheng
	 * @date 2018/7/13 11:17
	 */
	@RequestMapping(value = "getGoodsListByIds")
	@ResponseBody
	public List<BizGoods> getGoodsListByIds(HttpServletRequest request) {
		//goodsIds 商品的id（多个用，隔开）
		String[] goodsIds = request.getParameterValues("goodsIds[]");
		List<String> ids = Arrays.asList(goodsIds);
		List<BizGoods> goodsList = bizGoodsService.selectGoodsListByIds(ids);
		return goodsList;
	}

	/**
	 * 测试商品库存预警发送通知和邮件
	 * @return
	 * @author xuchen
	 * @date 2018/7/16
	 */
	/*@RequestMapping(value = "findWarningGoods")
	@ResponseBody
	public List<BizGoods> findWarningGoods() {
		List<BizGoods> goodsList = bizGoodsService.findAllWarningGoodsList(new BizGoods());
		sendMailAndOaNotify(goodsList, "xuchenchen@beepchina.cn");
		return goodsList;
	}*/


	/**
	 * 测试商品库存预警发送通知和邮件
	 * @param goodsList
	 * @param toMailAddr
	 */
	/*public void sendMailAndOaNotify(List<BizGoods> goodsList, String toMailAddr) {
		SendMailUtil.sendCommonMail(goodsList, toMailAddr);
		StringBuffer sb = new StringBuffer();
		for (BizGoods goods : goodsList) {
			sb.append("仓库：" + goods.getStorageName() + ",商品名称：" + goods.getGoodsName() + ",商品库存："
					+ goods.getStockAmount() + ",警戒库存：" + goods.getWarningAmount() + "\n");
		}
		OaNotify oaNotify = SendMailUtil.findOaNotify("4", "1", sb.toString(), "库存警戒通知");
		oaNotifyService.save(oaNotify);
	}*/

	/**
	 * 下载导入商品模板
	 * xuchen
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "ERP商品导入模板.xlsx";
			List<BizGoods> list = new ArrayList<BizGoods>();
			new ExportExcel("推荐客户数据", BizGoods.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
	}


	/**
	 * 导入商品数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */

	@RequestMapping(value = "importGoods", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<BizGoods> list = ei.getDataList(BizGoods.class);
			for (BizGoods bizGoods : list){
				try{
					Integer num = bizGoodsService.getStockAmountByGoodsCode(bizGoods.getGoodsCode());
					if(num == null || num == 0){
						BeanValidators.validateWithException(validator, bizGoods);
						Map<String, Object> Info = bizGoodsService.importGoods(bizGoods,failureMsg);
						//返回信息并判断
						failureMsg = (StringBuilder)Info.get("failureMsg");
						if((boolean)Info.get("isCanSave")){
							successNum++;
						}else{
							failureNum++;
						}
					}else{
						failureMsg.append("<br/>商品编号 "+bizGoods.getGoodsCode()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>商品 "+bizGoods.getGoodsName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>商品 "+bizGoods.getGoodsName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条商品，导入信息如下：");
			}
			System.out.print("-------------"+failureMsg);
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条商品"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入商品失败！失败信息："+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
	}



	/**
	 * 导出ERP商品
	 * @param bizGoods 查询的信息
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */

	@RequestMapping(value = "export", method= RequestMethod.POST)
	public String exportFile(BizGoods bizGoods, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "ERP商品"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			List<BizGoods> list = bizGoodsService.findList(bizGoods);
			new ExportExcel("ERP商品", BizGoods.class).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出ERP商品失败！失败信息："+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/biz/bizGoods/?repage";
	}




	/**
	 * 根据商品ID查询库存信息
	 * @author xuchen
	 * @date 2018/10/13
	 * @param  goodsId 商品id
	 * @return 库存信息List
	 */
	@RequestMapping(value = "stockInfo")
	@ResponseBody
	public List<BizBarcode> stockInfo(String goodsId){
		BizBarcode bizBarcode = new BizBarcode();
		bizBarcode.setGoodsId(goodsId);
		List<BizBarcode> bizBarcodeList = bizBarcodeService.findList(bizBarcode);
		return bizBarcodeList;
	}
}